package com.charles.video.auth.controller;

import com.charles.video.api.model.MemberLogin;
import com.charles.video.auth.form.LoginForm;
import com.charles.video.auth.service.SysLoginService;
import com.charles.video.common.core.responseDomain.R;
import com.charles.video.common.core.utils.StringUtils;
import com.charles.video.common.security.auth.AuthUtil;
import com.charles.video.common.security.service.TokenService;
import com.charles.video.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author Charles-H
 * 
 * 令牌控制层
 */
@RestController
public class TokenController {

    @Autowired
    private SysLoginService sysLoginService;

    @Autowired
    private TokenService tokenService;
    
    /* 系统成员登录 */
    @PostMapping("/login")
    public R<?> login(@RequestBody LoginForm form) {
        MemberLogin memberInfo = sysLoginService.login(form.getMemberNum(), form.getPassword());
        return R.ok(tokenService.createToken(memberInfo));
    }
    
    /* 退出登录 */
    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StringUtils.isNotEmpty(token)) {
            AuthUtil.logoutByToken(token);
        }
        return R.ok();
    }

}
